﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;

using PowerCreator.LMS.Course.Entity;
using PowerCreator.LMS.Common.Script;
using PowerCreator.LMS.Web.Course;
using PowerCreator.LMS.Web.Catalog;
using PowerCreator.LMS.Common.Utils;
using PowerCreator.LMS.Web.DL.Project;
using Telerik.WebControls;

public partial class sysadmin_CourseManager_EditCourseInfo : PowerCreator.LMS.Web.Base.WebBasePage
{
    Catalog opCatalog = new Catalog();
    VirtualDirectory opVirtual = new VirtualDirectory();
    Course opCourse = new Course();
    PowerCreator.LMS.Web.DL.Project.TOAdvancedUser objAdvanceUser = new TOAdvancedUser();
    private PowerCreator.LMS.Web.DL.User.LoginEntity login = new PowerCreator.LMS.Web.DL.User.LoginEntity();
    private string url = "../login.aspx";

    protected void Page_Load(object sender, EventArgs e)
    {
        CheckUser();
        if (!IsPostBack)
        {
            string courseid = Request.QueryString["CourseID"].ToString();
            ViewState["CourseID"] = courseid;

            InitPage();

            BinderCatalog();
            BinderVirtual();
            BinderXueduan();
            BinderTeacher();

            BinderPage();
            BinderXueNian();
            BindTrainType();

            if (Request.QueryString["AddCourseType"] != null)
            {
                if (Request.QueryString["AddCourseType"].ToString() == "uploadPic")
                    BinderForm();
            }
        }
    }
    private void CheckUser()
    {
        if (Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO] == null)
        {
            Script.RedirectNewUrl(url);
        }
        else
        {
            login = (PowerCreator.LMS.Web.DL.User.LoginEntity)Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO];
            if (login == null)
            {
                Script.RedirectNewUrl(url);
            }
            else
            {
                if (login.VOAdvancedUser == null)
                {
                    Script.RedirectNewUrl(url);
                }
                else if (login.VOAdvancedUser.AUserGroup > 2)
                {
                    //Response.Write(login.VOAdvancedUser.AUserGroup.ToString());
                    //Response.End();
                    Script.ShowAndHistory("您无此权限！", -1);
                }
            }
        }


    }

    protected override void InitPage()
    {

        lbl_InfoTitle.Text = GetLanageValueByKey("lbl_EditCourseInfo_InfoTitle", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_CourseName.Text = GetLanageValueByKey("lbl_EditCourseInfo_CourseName", PowerCreator.LMS.Language.LanagetItemType.Page);
        //lbl_CourseType.Text = GetLanageValueByKey("lbl_EditCourseInfo_CourseType", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_TeacherName.Text = GetLanageValueByKey("lbl_EditCourseInfo_TeacherName", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_CourseCode.Text = GetLanageValueByKey("lbl_EditCourseInfo_CourseCode", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_Type.Text = GetLanageValueByKey("lbl_EditCourseInfo_Type", PowerCreator.LMS.Language.LanagetItemType.Page);
        //lbl_CourseAllowSelect.Text = GetLanageValueByKey("lbl_AddCourseInfo_CourseAllowSelect", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_CoursePeriod.Text = GetLanageValueByKey("lbl_EditCourseInfo_CoursePeriod", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_TextBox.Text = GetLanageValueByKey("lbl_EditCourseInfo_TextBox", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_VirtualDirectoryinfo.Text = GetLanageValueByKey("lbl_EditCourseInfo_VirtualDirectoryinfo", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_VirtualDirectory.Text = GetLanageValueByKey("lbl_EditCourseInfo_VirtualDirectory", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_Stateinfo.Text = GetLanageValueByKey("lbl_EditCourseInfo_Stateinfo", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_State.Text = GetLanageValueByKey("lbl_EditCourseInfo_State", PowerCreator.LMS.Language.LanagetItemType.Page);

        //lbl_CourseIsRecommend.Text = "推荐课程";
        //lbl_CourseIsRecommendtxt.Text = "注：如果定位为推荐课程，请选择此项，同时推荐课程必须要上传图片！";
        //lbl_CourseImgUrl.Text = "图片";
        //lbl_UploadFile.Text = "<a href=\"#\" onclick=\"openUploadFile(" + ViewState["CourseID"].ToString() + ")\">上传图片</a>（注意：允许不上传图片）";
        lbl_CourseIsRecommend.Text = GetLanageValueByKey("AddCourseInfo_lbl_l2", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_CourseIsRecommendtxt.Text = GetLanageValueByKey("AddCourseInfo_lbl_l3", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_CourseImgUrl.Text = GetLanageValueByKey("AddCourseInfo_lbl_l4", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_FileUpload_msg_FileType.Text = GetLanageValueByKey("AddCourseInfo_lbl_l5", PowerCreator.LMS.Language.LanagetItemType.Page);

        //rdbtnBiXiu.Text = GetLanageValueByKey("Course_db_d1", PowerCreator.LMS.Language.LanagetItemType.Page);
        //rdbtnXuanXiu.Text = GetLanageValueByKey("Course_db_d2", PowerCreator.LMS.Language.LanagetItemType.Page);
        //rdbtnGongKai.Text = GetLanageValueByKey("Course_db_d3", PowerCreator.LMS.Language.LanagetItemType.Page);
        rfv_CourseName.ErrorMessage = GetLanageValueByKey("AddCourseInfo_msg_m1", PowerCreator.LMS.Language.LanagetItemType.Page);
        rdbtn_stateOK.Text = GetLanageValueByKey("AddCourseInfo_db_d1", PowerCreator.LMS.Language.LanagetItemType.Page);
        rdbtn_stateNO.Text = GetLanageValueByKey("AddCourseInfo_db_d2", PowerCreator.LMS.Language.LanagetItemType.Page);

        //rbtn_Yes.Text = GetLanageValueByKey("Course_db_d4", PowerCreator.LMS.Language.LanagetItemType.Page);
        //rbtn_No.Text = GetLanageValueByKey("Course_db_d5", PowerCreator.LMS.Language.LanagetItemType.Page);

        btn_Save.Text = GetLanageValueByKey("btn_EditCourseInfo_Save", PowerCreator.LMS.Language.LanagetItemType.Page);
        btn_Reset.Text = GetLanageValueByKey("btn_EditCourseInfo_Reset", PowerCreator.LMS.Language.LanagetItemType.Page);

        base.InitPage();
    }
    private void BinderCatalog()
    {
        string search = "";
        DataTable dt = opCatalog.QueryCatalog(search);
        ArrayList list = opCatalog.GetCatalogTree(dt);
        ddl_Catalog.DataSource = list;
        ddl_Catalog.DataTextField = "Text";
        ddl_Catalog.DataValueField = "Value";
        ddl_Catalog.DataBind();
    }

    private void BinderXueduan()
    {
        TOSchoolStage obj = new TOSchoolStage();
        string search = "";
        DataTable dt = obj.Query(search);

        ddl_xueduan.DataSource = dt;
        ddl_xueduan.DataTextField = "SchoolStage";
        ddl_xueduan.DataValueField = "ID";
        ddl_xueduan.DataBind();

    }
    private void BinderVirtual()
    {
        string search = "";
        DataTable dt = opVirtual.QueryVirtual(search);
        ddlVirtualDirectory.DataSource = dt;
        ddlVirtualDirectory.DataTextField = "VirIisName";
        ddlVirtualDirectory.DataValueField = "VirId";
        ddlVirtualDirectory.DataBind();
    }
    private void BinderTeacher()
    {
        string search = "";
        DataTable dt = objAdvanceUser.Query(search);
        ddl_CourseMostlyTeacher.DataSource = dt;
        ddl_CourseMostlyTeacher.DataTextField = "Name";
        ddl_CourseMostlyTeacher.DataValueField = "AUser_Id";
        ddl_CourseMostlyTeacher.DataBind();
    }
    private void BinderXueNian()
    {
        TOXuenian obj = new TOXuenian();
        string search = "";
        DataTable dt = obj.Query(search);
        ddl_xuenian.DataSource = dt;
        ddl_xuenian.DataTextField = "XueNian";
        ddl_xuenian.DataValueField = "ID";
        ddl_xuenian.DataBind();
    }
    
    private void BinderPage()
    {
        VOTOCourse vo = opCourse.LoadVOTCourse(int.Parse(ViewState["CourseID"].ToString()));
        if (vo != null)
        {
            txt_CourseName.Text = vo.CourseName;
            txt_CourseID.Text = vo.CourseID;
            txt_CourseCode.Text = vo.CourseCode;
            ddl_CourseMostlyTeacher.SelectedValue = vo.FKCourseMostlyTeacherID.ToString();
            txt_CoursePeriod.Text = vo.CoursePeriod.ToString();
            txt_xuefen.Text = vo.Score.ToString();
            if (txt_xuefen.Text == "")
                txt_xuefen.Text = "0";
            if(int.Parse(txt_xuefen.Text)<0)
                txt_xuefen.Text = "0";
            FreeTextBox1.Text = vo.Description;
            if (vo.CourseIsCompulsory == 1)
                rdbtnBiXiu.Checked = true;
            else if (vo.CourseIsCompulsory == 2)
                rdbtnXuanXiu.Checked = true;
            //else if (vo.CourseIsCompulsory == 3)
            //    rdbtnGongKai.Checked = true;
            if (vo.CourseIsRecommend == 1)
                cb_CourseIsRecommend.Checked = true;
            //if (vo.CourseAllowSelect == 1)
            //    rbtn_Yes.Checked = true;
            //else
            //    rbtn_No.Checked = true;
            txt_pic.Text = vo.CourseImgUrl;
            ddlVirtualDirectory.SelectedValue = vo.FKCourseVirId.ToString();
            ddl_xuenian.SelectedValue = vo.XueNian.ToString();
            ddl_Catalog.SelectedValue = vo.Xueke.ToString();
            ddl_xueduan.SelectedValue = vo.Xueduan.ToString();
            if (vo.TrainFormat != null)
            {
                if (vo.TrainFormat < 1)
                    ddl_peixunxingshi.SelectedValue = vo.TrainFormat.ToString();
            }

            if (vo.CourseState == 0)
            {
                rdbtn_stateNO.Checked = true;
                rdbtn_stateOK.Checked = false;
            }
            else if (vo.CourseState == 1)
            {
                rdbtn_stateOK.Checked = true;
                rdbtn_stateNO.Checked = false;
            }
            if (vo.Used)
            {
                rdbtn_Used_Yes.Checked = true;
                rdbtn_Used_No.Checked = false;
            }
            else
            {
                rdbtn_Used_Yes.Checked = false;
                rdbtn_Used_No.Checked = true;
            }
            BindTrainType();
        }
    }

    private void BinderForm()
    {
        //txt_CourseName.Text = Request.QueryString["coursename"].ToString();
        txt_pic.Text = Request.QueryString["picpath"].ToString();
        txt_pic.ReadOnly = true;
    }


    /// <summary>
    /// 绑定培训班信息
    /// </summary>
    private void BindTrainType()
    {
        TOTrainType obj = new TOTrainType();

        Hashtable hs = new Hashtable();
        ArrayList list = new ArrayList();

        if (ViewState["CourseID"] != null)
        {

            string search = string.Format("Course_Id={0}", ViewState["CourseID"].ToString());
            DataTable dt2 = opCourse.Query(search);
            if (dt2.Rows.Count == 1)
            {
                string[] traintypeIDs = dt2.Rows[0]["TrainType"].ToString().Split(',');
                for (int i = 0; i < traintypeIDs.Length; i++)
                {
                    hs.Add(traintypeIDs[i].ToString(), "1");
                }
            }

        }

        DataTable dt = obj.Query("");
        chk_peixunleixing.DataSource = dt;
        chk_peixunleixing.DataTextField = "ShortName";
        chk_peixunleixing.DataValueField = "ID";
        chk_peixunleixing.DataBind();

        if (ViewState["CourseID"] != null)
        {
            for (int j = 0; j < chk_peixunleixing.Items.Count; j++)
            {
                if (hs.ContainsKey(chk_peixunleixing.Items[j].Value))
                    chk_peixunleixing.Items[j].Selected = true;
            }
        }

    }

    private bool CheckPageData()
    {
        if (!IntUtils.IsNumber(txt_CoursePeriod.Text))
        {
            lbl_editcourseinfo_msg_courseperiod.Text = GetLanageValueByKey("lbl_editcourseinfo_msg_courseperiod", PowerCreator.LMS.Language.LanagetItemType.MSG);
            return false;
        }
        if (string.IsNullOrEmpty(ddlVirtualDirectory.SelectedValue.ToString()))
        {
            lbl_editcourseinfo_msg_virtual.Text = GetLanageValueByKey("lbl_editcourseinfo_msg_virtual", PowerCreator.LMS.Language.LanagetItemType.MSG);
            return false;
        }
        return true;
    }

    protected void btn_Save_Click(object sender, EventArgs e)
    {
        if (!CheckPageData()) return;

        VOTOCourse vo = opCourse.LoadVOTCourse(int.Parse(ViewState["CourseID"].ToString()));
        vo.CourseCode = txt_CourseCode.Text;
        vo.CourseID = txt_CourseID.Text.Trim();
        vo.Description = FreeTextBox1.Text;

        vo.CourseIsCompulsory = 1;
        if (rdbtnXuanXiu.Checked)
            vo.CourseIsCompulsory = 2;
        //else if (rdbtnGongKai.Checked)
        //    vo.CourseIsCompulsory = 3;

        vo.CourseImgUrl = txt_pic.Text.Trim();
        if (cb_CourseIsRecommend.Checked == true)
            vo.CourseIsRecommend = 1;
        else
            vo.CourseIsRecommend = 0;
        //if (rbtn_Yes.Checked == true)
        //    vo.CourseAllowSelect = 1;
        //else
        //    vo.CourseAllowSelect = 0;

        vo.CourseLastUpdateTime = DateTime.Now;
        vo.FKCourseMostlyTeacherID = int.Parse(ddl_CourseMostlyTeacher.SelectedValue);
        vo.CourseMostlyTeacherName = ddl_CourseMostlyTeacher.SelectedItem.Text;
        vo.CourseName = txt_CourseName.Text;

        vo.CoursePeriod = int.Parse(txt_CoursePeriod.Text);
        vo.Score = int.Parse(txt_xuefen.Text.Trim());
        vo.XueNian = int.Parse(ddl_xuenian.SelectedValue);
        vo.TrainFormat = int.Parse(ddl_peixunxingshi.SelectedValue);
        vo.TrainType = getTrainTypeIDlist();

        vo.FKCourseVirId = int.Parse(ddlVirtualDirectory.SelectedValue);
        PowerCreator.LMS.Web.Base.BasePage bpage = new PowerCreator.LMS.Web.Base.BasePage();
        vo.FKCourseCreatorid = bpage.GetCreatedByInfo().UserID;

        vo.CourseState = 0;
        if (rdbtn_stateOK.Checked)
            vo.CourseState = 1;
        if (rdbtn_Used_Yes.Checked)
            vo.Used = true;
        else
            vo.Used = false;

        vo.Xueduan = int.Parse(ddl_xueduan.SelectedValue);
        vo.Xueke = int.Parse(ddl_Catalog.SelectedValue);
        if(opCourse.UpdateCourse(vo))
        {
            string url = "Course.aspx";
            Script.RedirectURL(url);
        }
    }

    private string getTrainTypeIDlist()
    {
        string trainTypeIDlist = "-1,";

        for (int j = 0; j < chk_peixunleixing.Items.Count; j++)
        {
            if (chk_peixunleixing.Items[j].Selected)
            {
                trainTypeIDlist += chk_peixunleixing.Items[j].Value + ",";
            }
        }
        trainTypeIDlist += "0";
        if (trainTypeIDlist == "-1,0")
            trainTypeIDlist = "0";
        return trainTypeIDlist;
    }
    protected void btn_Back_Click(object sender, EventArgs e)
    {
        string url = "Course.aspx";
        Script.RedirectURL(url);
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        //btn_Back.Enabled = false;
        foreach (UploadedFile file in RadUploadContext.Current.UploadedFiles)
        {
            string Url = "";
            Url = WebUtils.WebRoot + "/fileManager/UploadFile/CoursePic/";
            string Path = Server.MapPath(Url);

            //如果路径不存在，则创建
            if (System.IO.Directory.Exists(Path) == false)
            {
                System.IO.Directory.CreateDirectory(Path);
            }

            string filetype = file.GetExtension();
            if (!IsUploadFileType(filetype)) return;

            //组合路径，file.GetName()取得文件名
            string fileName = opCourse.GetUploadResourceFileName(file.GetExtension());

            Path = Path + fileName;
            Url = Url + fileName;
            //保存
            file.SaveAs(Path, true);
            txt_pic.Text = Url;
            btn_Back.Enabled = true;
        }
    }

    //检查上传文件类型
    public bool IsUploadFileType(string extension)
    {
        string allowExtensions = "gif|jpg";    //允许上传的类型
        if (!opCourse.IsAllowedExtension(extension, allowExtensions))
        {
            lbl_FileUpload_msg_FileType.Text = GetLanageValueByKey("AddCourseInfo_msg_m2", PowerCreator.LMS.Language.LanagetItemType.Page) + allowExtensions;
            return false;
        }
        return true;
    }
}
